package edu.spec.student.service.impl;

import edu.spec.student.dao.iface.IQuestionnaireDao;
import edu.spec.student.dao.iface.ISubjectDao;
import edu.spec.student.model.questionnaire.Questionnaire;
import edu.spec.student.model.questionnaire.Subject;
import edu.spec.student.service.iface.ISubjectService;
import edu.spec.basic.util.FileTool;
import edu.spec.basic.util.XlsTools;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Collection;
import java.util.List;

/**
 * Author       : MadFrog
 * Date         : 2018/7/6 14:19
 * Description  :
 */
@Service
public class SubjectService implements ISubjectService {

    @Inject
    private ISubjectDao subjectDao;
    @Inject
    private IQuestionnaireDao questionnaireDao;

    @Override
    public void add(Subject subject) {
        subjectDao.add(subject);
    }

    @Override
    public List<Subject> listSubjectByQuestionnaire(Integer questionnaireId) {
        return subjectDao.listSubjectByQuestionnaire(questionnaireId);
    }

    @Override
    public boolean importIn(Integer questionnaireId, MultipartFile file, HttpServletRequest req) {
        String fullStorePath = FileTool.saveTempFile(file, req);
        File importFile = new File(fullStorePath);
        Questionnaire questionnaire = questionnaireDao.load(questionnaireId);
        Collection col = XlsTools.importExcel(importFile, Subject.class, "");
        for(Object o : col){
            Subject s = (Subject) o;
            s.setQuestionnaire(questionnaire);
            this.add(s);
        }
        importFile.delete();
        return true;
    }
}
